package com.elh.serurity.controller;

import com.google.code.kaptcha.Producer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author liulei
 */
@Controller
public class CaptchaController {

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @GetMapping(value = "/captcha.jpg")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        String capStr = null, code = null;
        BufferedImage image = null;
        capStr = code = captchaProducer.createText();
        HttpSession session = request.getSession();
        session.setAttribute("captcha", capStr);
        image = captchaProducer.createImage(capStr);
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            ImageIO.write(image, "jpg", out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
